/*************************************************************
 * File: MenuResource.java
 * Copyright (c) 2012
 * Author: Huang Shaobin
 * Email: Shaobin.Software@gmail.com Shaobin_Software@163.com 
 * Date: Feb 23, 2013
 * Description: 
 ************************************************************/

package snow.biz.system.web.rest;

import java.util.Arrays;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.restlet.data.Form;

import snow.biz.system.model.Menu;
import snow.biz.system.service.IMenuService;
import snow.core.persistence.AndedConditions;
import snow.core.persistence.BinaryOperator;
import snow.core.persistence.Condition;
import snow.core.persistence.Conditions;
import snow.core.persistence.EntityHelper;
import snow.core.persistence.Order;
import snow.core.security.Operator;
import snow.core.security.annotations.Operation;
import snow.core.security.annotations.Resource;
import snow.core.web.rest.ResourceSupport;

/**
 * 菜单服务
 * 
 * @author Shaobin.Software@gmail.com Shaobin_Software@163.com
 * @version 1.0
 */
@Path("/system/menus")
@Resource(uri = "/menus")
public class MenuResource extends ResourceSupport {

	private IMenuService menuService;

	public IMenuService getMenuService() {
		return this.menuService;
	}

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Operation(name = "显示菜单列表", type = Operator.SEARCH, needCheck = false)
	public Object listMenus() {
		final Form queryForm = super.getQueryAsForm();
		final Conditions conditions = new AndedConditions();
		final int parentId = NumberUtils.toInt(queryForm.getFirstValue("parentId"), -1);
		final Menu superior = menuService.searchMenuFrom(Integer.valueOf(parentId));
		if (EntityHelper.validate(superior)) {
			conditions.addCondition(new Condition("superior", BinaryOperator.EQ, superior));
		} else if (BooleanUtils.toBoolean(queryForm.getFirstValue("asMenu"))) {
			conditions.addCondition(new Condition("superior", Condition.IS_NULL));
		}
		final String text = queryForm.getFirstValue("text");
		if (StringUtils.isNotBlank(text)) {
			conditions.addCondition(new Condition("text", BinaryOperator.LIKE, text.trim()));
		}
		final int start = NumberUtils.toInt(queryForm.getFirstValue("start"), -1);
		final int limit = NumberUtils.toInt(queryForm.getFirstValue("limit"), -1);
		return menuService.searchMenusForPagingFrom(conditions, Arrays.asList(new Order[] { Order.desc("sort"), Order.desc("id") }), start, limit);
	}

	public void setMenuService(IMenuService menuService) {
		this.menuService = menuService;
	}

}
